<!--发生费用-->
<template>
    <div class="cost">
        <Row>
            <iCol span="11">  <!-- left table -->
                <Button type="primary" size="small" class="new-button" icon="md-add" @click="newCost(1)">新增</Button>
                <table class="cost-table left-table" cellpadding="0" cellspacing="0" width="100%">
                    <thead>
                        <tr>
                            <th width="10%">
                                <Checkbox v-model="leftCheckAll" @on-change="checkAllHandle(1, leftCheckAll)"></Checkbox>
                            </th>
                            <th width="25%">
                                费用名称
                            </th>
                            <th width="15%">
                                金额
                            </th>
                            <th width="25%">
                                币制
                            </th>
                            <th width="25%">
                                管理
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item, index) in leftData" :key="index" @dblclick="edit(1, item, leftData)">
                            <td>  <!--Checkbox-->
                                <Checkbox v-model="item.isChecked" @on-change="checkedChange(1)"></Checkbox>
                            </td>
                            <td>   <!--费用名称-->
                                <span v-if="!item.isEdit">{{ item.expAccName }}</span>
                                <Select
                                    v-else
                                    size="small"
                                    v-model="item.expAccId"
                                    filterable
                                    style="text-align: left;"
                                    class="td-expAccId"
                                >
                                    <Option
                                        v-for="(option, index) in accountList"
                                        :key="index"
                                        :value="option.expAccId"
                                        :label="option.expAccName"
                                    >
                                    </Option>
                                </Select>
                            </td>
                            <td> <!--金额-->
                                <span v-if="!item.isEdit">{{ item.expAmount }}</span>
                                <Input v-else v-model="item.expAmount" size="small" class="td-expAmount"></Input>
                            </td>
                            <td>  <!--币制-->
                                <span v-if="!item.isEdit">{{ item.currencyName }}</span>
                                <Select
                                    v-else
                                    size="small"
                                    v-model="item.currencyCode"
                                    filterable
                                    style="text-align: left;"
                                    class="td-currencyCode"
                                >
                                    <Option
                                        v-for="(option, index) in currencyCodeList"
                                        :key="index"
                                        :value="option.dataCode"
                                        :label="option.dataName"
                                    >
                                    </Option>
                                </Select>
                            </td>
                            <td class="manage-box">
                                <Button type="primary" size="small" v-if="!item.isEdit" @click="edit(1, item, leftData)">编辑</Button>
                                <Button type="error" size="small" v-if="!item.isEdit" @click="remove(1, item, index)">删除</Button>
                                <Button type="primary" size="small" v-if="item.isEdit" @click="save(1, item)">保存</Button>
                                <Button type="error" size="small" v-if="item.isEdit" @click="cancel(1)">取消</Button>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <p class="total">
                    <span>合计：</span>
                    <span>{{ leftTotal }}</span>
                </p>
            </iCol>
            <iCol span="2">
                <div class="arrows">
                    <p></p>
                    <p></p>
                </div>
            </iCol>
            <iCol span="11">   <!-- right table -->
                <Button type="primary" size="small" class="new-button" icon="md-add" @click="newCost(2)">新增</Button>
                <table class="cost-table  right-table" cellpadding="0" cellspacing="0" width="100%">
                    <thead>
                        <tr>
                            <th width="10%">
                                <Checkbox v-model="rightCheckAll" @on-change="checkAllHandle(2, rightCheckAll)"></Checkbox>
                            </th>
                            <th width="20%">
                                服务商
                            </th>
                            <th width="20%">
                                费用名称
                            </th>
                            <th width="15%">
                                金额
                            </th>
                            <th width="15%">
                                币制
                            </th>
                            <th width="20%">
                                管理
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item, index) in rightData" :key="index" @dblclick="edit(2, item, rightData)">
                            <td>  <!--Checkbox-->
                                <Checkbox v-model="item.isChecked" @on-change="checkedChange(2)"></Checkbox>
                            </td>
                            <td>  <!--服务商-->
                                <span v-if="!item.isEdit">{{ item.supplierName }}</span>
                                <Select
                                    v-else
                                    size="small"
                                    v-model="item.supplierId"
                                    filterable
                                    style="text-align: left;"
                                    class="td-supplierId"
                                >
                                    <Option
                                        v-for="(option, index) in supplierList"
                                        :key="index"
                                        :value="option.supplierId"
                                        :label="option.supplierName"
                                    >
                                    </Option>
                                </Select>
                            </td>
                            <td>   <!--费用名称-->
                                <span v-if="!item.isEdit">{{ item.expAccName }}</span>
                                <Select
                                    v-else
                                    size="small"
                                    v-model="item.expAccId"
                                    filterable
                                    style="text-align: left;"
                                    class="td-expAccId"
                                >
                                    <Option
                                        v-for="(option, index) in accountList"
                                        :key="index"
                                        :value="option.expAccId"
                                        :label="option.expAccName"
                                    >
                                    </Option>
                                </Select>
                            </td>
                            <td> <!--金额-->
                                <span v-if="!item.isEdit">{{ item.expAmount }}</span>
                                <Input v-else v-model="item.expAmount" size="small" class="td-expAmount"></Input>
                            </td>
                            <td>  <!--币制-->
                                <span v-if="!item.isEdit">{{ item.currencyName }}</span>
                                <Select
                                    v-else
                                    size="small"
                                    v-model="item.currencyCode"
                                    filterable
                                    style="text-align: left;"
                                    class="td-currencyCode"
                                >
                                    <Option
                                        v-for="(option, index) in currencyCodeList"
                                        :key="index"
                                        :value="option.dataCode"
                                        :label="option.dataName"
                                    >
                                    </Option>
                                </Select>
                            </td>
                            <td class="manage-box">
                                <Button type="primary" size="small" v-if="!item.isEdit" @click="edit(2, item, rightData)">编辑</Button>
                                <Button type="error" size="small" v-if="!item.isEdit" @click="remove(2, item, index)">删除</Button>
                                <Button type="primary" size="small" v-if="item.isEdit" @click="save(2, item)">保存</Button>
                                <Button type="error" size="small" v-if="item.isEdit" @click="cancel(2)">取消</Button>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <p class="total right-total">
                    <span>合计：</span>
                    <span>{{ rightTotal }}</span>
                </p>
            </iCol>
        </Row>
    </div>
</template>

<script>
import { httpGet, httpPost } from '@/libs/http'
import { getToken } from '@/libs/util.js'
import { getDicByKey } from '@/libs/getDicDataList'
import $ from 'jquery'

export default {
    name: 'Cost',
    data () {
        return {
            declareId: '',
            leftCheckAll: false,
            leftData: [],
            leftTotal: 0,
            originLeftData: [],

            rightCheckAll: false,
            rightData: [],
            rightTotal: 0,
            originRightData: [],

            accountList: [],
            supplierList: [],
            currencyCodeList: []
        }
    },

    created () {
        this.init()
    },

    methods: {
        init (declareId) {
            if (declareId) {
                this.declareId = declareId
                this.getBaseList().then(() => {
                    this.getTableData(declareId, 1)
                    this.getTableData(declareId, 2)
                })
            }
        },

        async getBaseList () {
            await this.queryAccountList()
            await this.querySuppliers()
            await getDicByKey('CURRENCY_CODE').then(list => {
                this.currencyCodeList = list
            })
        },

        queryAccountList () {
            let data = {
                condition: '',
                pageNum: 1,
                pageSize: 10000
            }
            let url = '/financialManagement/expense/queryAccountList'
            httpPost(url, data).then(res => {
                if (res.code === '0000') {
                    this.accountList = res.data.list
                }
            })
        },

        querySuppliers () {
            let data = {
                pageNum: 1,
                pageSize: 10000,
                supplierName: ''
            }
            let url = '/supplier/querySuppliers'
            httpPost(url, data).then(res => {
                if (res.code === '0000') {
                    this.supplierList = res.data.list
                }
            })
        },

        getTableData (declareId, expType) {
            let url = '/ui/customs/declareExpense/list?declareId=' + declareId + '&expType=' + expType + '&Authorization=' + getToken()
            httpGet(url).then(res => {
                if (res.code === '0000' && Array.isArray(res.data)) {
                    res.data.forEach(item => {
                        item.isChecked = false
                        item.isEdit = false
                    })
                    if (expType === 1) {
                        this.leftData = res.data
                        this.originLeftData = JSON.parse(JSON.stringify(this.leftData))
                        this.getTotal(1)
                    } else {
                        this.rightData = res.data
                        this.originRightData = JSON.parse(JSON.stringify(this.rightData))
                        this.getTotal(2)
                    }
                }
            })
        },

        checkAllHandle (type, state) {
            switch (type) {
                case 1:
                    this.leftData.forEach(item => {
                        item.isChecked = state
                    })
                    break
                case 2:
                    this.rightData.forEach(item => {
                        item.isChecked = state
                    })
                    break
            }
        },

        checkedChange (type) {
            switch (type) {
                case 1:
                    let tempArr1 = []
                    this.leftData.forEach(item => {
                        if (item.isChecked) {
                            tempArr1.push(item)
                        }
                    })
                    if (tempArr1.length === this.leftData.length) {
                        this.leftCheckAll = true
                    } else {
                        this.leftCheckAll = false
                    }
                    break
                case 2:
                    let tempArr2 = []
                    this.rightData.forEach(item => {
                        if (item.isChecked) {
                            tempArr2.push(item)
                        }
                    })
                    if (tempArr2.length === this.rightData.length) {
                        this.rightCheckAll = true
                    } else {
                        this.rightCheckAll = false
                    }
                    break
            }
        },

        edit (type, data, list) {
            let isHasEdit = false
            if (list.length > 0) {
                list.forEach(item => {
                    if (item.isEdit) {
                        isHasEdit = true
                    }
                })
            }

            if (isHasEdit) {
                this.$Message.warning('请先保存正在编辑的数据')
            } else {
                data.isEdit = true
            }
        },

        remove (type, data, index) {
            let url = '/ui/customs/declareExpense/delete?declareExpenseId=' + data.declareExpenseId + '&Authorization=' + getToken()
            this.$Modal.confirm({
                title: '提示',
                content: '<p>确定要删除数据吗？</p>',
                okText: '确定',
                cancelText: '取消',
                onOk: () => {
                    httpGet(url).then(res => {
                        if (res.code === '0000') {
                            this.$Message.success('删除成功')
                            if (type === 1) {
                                this.leftData.splice(index, 1)
                                this.originLeftData = JSON.parse(JSON.stringify(this.leftData))
                                this.getTotal(type)
                            } else {
                                this.rightData.splice(index, 1)
                                this.originRightData = JSON.parse(JSON.stringify(this.rightData))
                                this.getTotal(type)
                            }
                        }
                    })
                }
            })
        },

        newCost (type) {
            let isHasEdit = false
            let list = type === 1 ? this.leftData : this.rightData
            if (list.length > 0) {
                list.forEach(item => {
                    if (item.isEdit) {
                        isHasEdit = true
                    }
                })
            }

            if (isHasEdit) {
                this.$Message.warning('请先保存正在编辑的数据')
                return false
            }

            let obj = {
                expAccName: '',
                expAccId: '',
                expAmount: 0,
                currencyCode: 'CNY',
                currencyName: '人民币',
                declareExpenseId: '',
                supplierId: '',
                supplierName: '',
                isChecked: false,
                isEdit: true
            }

            if (type === 1) {
                this.leftData.push(obj)
                this.$nextTick(() => {
                    $('.left-table .td-expAccId').last().find('.ivu-select-input').focus()
                })
            } else {
                this.rightData.push(obj)
                this.$nextTick(() => {
                    $('.right-table .td-supplierId').last().find('.ivu-select-input').focus()
                })
            }
        },

        save (type, data) {
            let isPass = true
            switch (type) {
                case 1:
                    if (!data.expAccId || !data.expAmount.toString() || !data.currencyCode) {
                        this.$Message.warning('请检查费用名称，金额，币制是否都已录入？')
                        isPass = false
                    }
                    break
                case 2:
                    if (!data.supplierId || !data.expAccId || !data.expAmount.toString() || !data.currencyCode) {
                        this.$Message.warning('请检查服务商，费用名称，金额，币制是否都已录入？')
                        isPass = false
                    }
                    break
            }

            if (!isPass) {
                return false
            }

            let reg = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,4})?$/ // 金额是非负数且保留4位小数
            if (!reg.test(data.expAmount)) {
                this.$Message.warning('金额是非负数且保留4位小数')
                isPass = false
            }

            if (!isPass) {
                return false
            }

            let params = {
                currencyCode: data.currencyCode,
                declareExpenseId: data.declareExpenseId || '',
                declareId: this.declareId,
                expAccId: data.expAccId,
                expAmount: data.expAmount,
                expType: type,
                supplierId: data.supplierId || ''
            }
            let url = '/ui/customs/declareExpense/addOrEdit'
            httpPost(url, params).then(res => {
                if (res.code === '0000') {
                    this.$Message.success('保存成功！')
                    this.getTableData(this.declareId, type)
                    if (type === 1) {
                        this.originLeftData = JSON.parse(JSON.stringify(this.leftData))
                        this.getTotal(type)
                    } else {
                        this.originRightData = JSON.parse(JSON.stringify(this.rightData))
                        this.getTotal(type)
                    }
                }
            })
        },

        cancel (type) {
            if (type === 1) {
                this.leftData = JSON.parse(JSON.stringify(this.originLeftData))
            } else {
                this.rightData = JSON.parse(JSON.stringify(this.originRightData))
            }
        },

        getTotal (type) {
            switch (type) {
                case 1:
                    let total1 = 0
                    if (this.leftData.length > 0) {
                        this.leftData.forEach(item => {
                            total1 += Number(item.expAmount) * 0.01 * 100
                        })
                    }
                    this.leftTotal = (total1).toFixed(4)
                    break
                case 2:
                    let total2 = 0
                    if (this.rightData.length > 0) {
                        this.rightData.forEach(item => {
                            total2 += Number(item.expAmount) * 0.01 * 100
                        })
                    }
                    this.rightTotal = (total2).toFixed(4)
                    break
            }
        }

    } // methods end
}
</script>

<style lang="less" scoped>
    .cost {
        .new-button {
            margin-bottom: 10px;
        }

        .cost-table {
            border: 1px solid #e8eaec;
            border-bottom: 0;

            th, td {
                padding: 10px 0;
                border-bottom: 1px solid #e8eaec;
            }

            thead {
                text-align: left;
                background-color: #f8f8f9;
                border-bottom: 1px solid #e8eaec;
                cursor: pointer;

                & > tr > th{
                    text-align: center;
                }
            }

            tbody {
                tr {
                    cursor: pointer;

                    &:hover, &:active {
                        background-color: #f8f8f9;
                    }
                }

                tr > td {
                    text-align: center;
                    /*padding: 0 3px;*/
                    padding: 3px;
                }
            }
            .manage-box {
                button {
                    margin-right: 10px;
                }
            }
        }

        .arrows {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding-top: 80px;
            > p {
                width: 15px;
                height: 15px;
                margin: 10px 0;
                cursor: pointer;
                background: url("../../../assets/icons/larrows.png");
                background-size: 100% 100%;

                &:last-child {
                    background: url("../../../assets/icons/rarrows.png");
                    background-size: 100% 100%;
                }
            }
        }

        .total {
            position: relative;
            margin-top: 10px;
            span:first-child {
                margin-left: 3%;
            }
            span:last-child {
                position: absolute;
                left: 36%;
                display: inline-block;
                width: 90px;
                text-align: center;
            }
        }

        .right-total {
            span:last-child {
                left: 52%;
            }
        }
    }
</style>
